/* GSExcelToManufacture.java
 *
 * Project/Product: APEP-JZCG
 *
 * Modify Information:
 * =============================================================================
 *   Author	Date       Description
 *   ----------	---------- ---------------------------------------------------
 *   peng.ning	2008-10-24	First release
 *
 * Licensed Materials - Property of APEP
 * =============================================================================
 *    (C) COPYRIGHT Shanghai Auto Mart E-Procurement Co., Ltd. 2007 - 2008
 *    All Rights Reserved.
 *
 *    This software is the confidential and proprietary information of
 *    Shanghai Auto Mart E-Procurement Co., Ltd. ("Confidential Information").
 *    You shall not disclose such Confidential Information and shall use it only
 *    in accordance with the terms of the license agreement you entered into 
 *    with Shanghai Auto Mart E-Procurement Co., Ltd.
 *
 * Noties:
 * =============================================================================
 * 
 */

package com.hitrust.gs.action;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.struts.upload.FormFile;

import system.data.ProductTaxData;
import system.imp.DateUtil;
import com.hitrust.gs.bean.GSManufactureBean;
import com.hitrust.gs.bean.GSProductTemporaryMaintainBean;
import com.hitrust.gs.bean.GSProductTypeManagerBean;
import com.hitrust.gs.bean.GSProductUpdateIsbuyBean;
import com.hitrust.gs.bean.GSProductUpdatePriceBean;
import com.hitrust.gs.bean.GSProviderBean;
import com.hitrust.gs.business.GSProviderProcessor;
import com.hitrust.gs.dao.GSManufactureDAO;
import com.hitrust.gs.dao.GSProductTaxDao;
import com.hitrust.gs.dao.GSProductTypeManagerDao;
import com.hitrust.gs.form.GSImportExcelForm;
import com.hitrust.gs.lib.GSBaseConstants;
import com.hitrust.gs.lib.GSLogWriter;
import com.hitrust.gs.service.GSBaseAction;
import com.hitrust.gs.service.GSBaseForm;
import com.hitrust.gs.util.RegulaUtil;
import com.hitrust.gs.util.exception.GSException;
import com.hitrust.gs.util.page.ResultProcess;
import com.hitrust.gs.vo.GSProductUpdateIsbuyView;

public class GSExcelToProductTax extends GSBaseAction {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.apep.jzcg.service.GSBaseAction#execute(com.apep.jzcg.service.GSBaseForm
	 * )
	 */

	public static final String SHEET_NAME_ON  = "产品启用信息";
	public static final String SHEET_NAME_OFF = "产品税务信息更新";
	public static final String SEP = "%";
	public static String[] HEAD_NAMES_ON = { "序号", "集中编码","启用日期","区域分类","招标分类","启用时间(小时)","启用时间(分钟)" };
	public static String[] HEAD_NAMES_OFF = { "集中编码","编码版本号","税收分类编码"};

	public boolean[] COL_CHECK_ON = new boolean[7];
	public boolean[] COL_CHECK_OFF = new boolean[3];

	public GSProductUpdateIsbuyView manuview = null;
	public ProductTaxData manuview2 = null;
	GSProviderProcessor ppro = new GSProviderProcessor();

	// 匹配不包括 ',",<,>,&的特殊字符
	public static final String regula = "[^'\"<>&]*";
	public static final String zhibao = "^\\d+$";


	public String execute(GSBaseForm aForm) throws Exception {
		GSImportExcelForm tGSImportExcelForm = (GSImportExcelForm) aForm;
		FormFile formFile = tGSImportExcelForm.getExcelfile();

		if (formFile != null) {
			String type=(String)aForm.getRequest().getParameter("type");
			
			ArrayList tList = loadDataFromExcel(formFile.getInputStream(),type,aForm);
			ResultProcess tProc = new ResultProcess();
			tProc.setResult(tList);
			ProductTaxData data = null;
			GSProductTaxDao ptdao = new GSProductTaxDao();
			List mytList = null;
			if("0".equals(type)){
			if(tList!=null&&tList.size()>0){
				for (int i=0;i<tList.size();i++) {
					data=(ProductTaxData)tList.get(i);
					mytList = ptdao.queryProductTaxIsOk(data.getProductCode());
					if(mytList!=null&&mytList.size()>0){
						ptdao.update(data.getProductCode(), data);
					}else{
						ptdao.insert(data);
					}
				}
			}
			}
			aForm.getRequest().setAttribute("type", type);
		}
		aForm.getRequest().setAttribute("action", "A1900054.do?type=0");
		return GSBaseConstants.FORWARD_SUCCESS;
	}

	/**
	 * 从Excel中载入格式化数据，数据项之间以分隔符%隔开
	 * 
	 * @param aInputStream
	 * @param aPage
	 * @param aPageSize
	 * @return
	 * @throws Exception
	 */
	public ArrayList loadDataFromExcel(InputStream aInputStream,String type,GSBaseForm aForm)
			throws Exception {

		ArrayList tPageDataList = new ArrayList();
		ArrayList concentricityCodeList = new ArrayList();
		Workbook tExcelWorkbook = null;

		try {
			tExcelWorkbook = Workbook.getWorkbook(aInputStream);
			Sheet tExcelSheet=null;
			if("0".equals(type)){
				 tExcelSheet = tExcelWorkbook.getSheet(SHEET_NAME_OFF);
			}else{
				 tExcelSheet = tExcelWorkbook.getSheet(SHEET_NAME_ON);
			}
			
			if (tExcelSheet == null) {
				if("0".equals(type)){
					aForm.getRequest().setAttribute("gohistory","true");	
					throw new GSException("批量导入产品税务信息失败:文件格式不正确,无法找到：" + SHEET_NAME_OFF);
				}else{
					aForm.getRequest().setAttribute("gohistory","true");	
					throw new GSException("批量导入产品启用信息失败:文件格式不正确,无法找到：" + SHEET_NAME_ON);
				}
			}
			for (int i = 1; i < tExcelSheet.getRows(); i++) {
				Cell tCells[] = tExcelSheet.getRow(i);
				String tRowText = "";
				int num = tCells.length;
				for (short j = 0; j < num; j++) {
					Cell tExcelCell = tCells[j];
					if (tExcelCell == null) {
						break;
					}
					String tCellValue = tExcelCell.getContents();
					if (tCellValue.length() == 0) {
						tCellValue = " ";
					}
					tRowText += tCellValue + SEP;
				}
				int headlength=0;
				if("0".equals(type)){
					headlength=HEAD_NAMES_OFF.length;
				}else{
					headlength=HEAD_NAMES_ON.length;
				}

				for (int a = num; a < headlength; a++) {
					tRowText += " " + SEP;
				}

				// 检查数据是否正确,如果和数据库中不符则将结果添加到末尾,从第二行开始
				if("0".equals(type)){
				tRowText = this.checkProductUpdateIsBuyOff(tRowText, i - 1,concentricityCodeList);
				}
				if("0".equals(type)){
					for (int tJ = 0; tJ < COL_CHECK_OFF.length; tJ++) {
						if (COL_CHECK_OFF[tJ] == false) {
							aForm.getRequest().setAttribute("gohistory","true");	
							throw new GSException(tRowText);
						}
					}
				}else{
					for (int tJ = 0; tJ < COL_CHECK_ON.length; tJ++) {
						if (COL_CHECK_ON[tJ] == false) {
							aForm.getRequest().setAttribute("gohistory","true");	
							throw new GSException(tRowText);
						}
					}	
				}			
				tPageDataList.add(manuview2);
				GSLogWriter.info(tRowText);
			}
		} catch (BiffException e) {
			GSLogWriter.error(e.getMessage());
		} catch (IOException e) {
			GSLogWriter.error(e.getMessage());
		} finally {
			if (tExcelWorkbook != null)
				tExcelWorkbook.close();
		}
		return tPageDataList;
	}

	
	
	/**
	 * 
			I.产品不存在不能导入
                      II．产品无效不能导入
                      III．关闭的情况判断产品是否是启用(可采购)。
                      IIII． 启用日期必须大于当前日期且格式符合要求
                      判断产品在启用日期之后有没有，未执行的调价或者替换，如果有提示存在在启用日期之后有调价或者替换，不能导入
                                IV.同一产品在相同启用日期里，如果存在待审批或者审批通过的记录，提示在启用日期里已经存在相同记录。

	 * 同一次导入产品编码不能重复
	 **/

	public String checkProductUpdateIsBuyOff(String aRowText, int a,ArrayList concentricityCodeList) throws Exception {
		manuview = new GSProductUpdateIsbuyView();
		for (int i = 0; i < COL_CHECK_OFF.length; i++) {
			COL_CHECK_OFF[i] = true;
		}

		String[] tRecorderColumns = aRowText.split(SEP);

		for (int i = 0; i < tRecorderColumns.length; i++) {
			if (!RegulaUtil.matchByString(tRecorderColumns[i], regula)) {
				COL_CHECK_OFF[i] = false;
				return HEAD_NAMES_OFF[0] + tRecorderColumns[0] + ": "
						+ HEAD_NAMES_OFF[i] + "不能为',\",<,>,&等特殊字符（第"+(a+2)+"行）!";
			}
		}

		

		GSManufactureDAO dao = new GSManufactureDAO();
		GSManufactureBean mbean = dao.getManufactureByConcentricityCode(
				tRecorderColumns[0].trim(), " select * from t_product ");
		if (mbean == null) {
			COL_CHECK_OFF[0] = false;
			return HEAD_NAMES_OFF[0] + tRecorderColumns[0] + ": " + HEAD_NAMES_OFF[0]
					+ "产品不存在（第"+(a+2)+"行）！";
		}
		if (mbean.getGs_validity().equals("0")) {
			COL_CHECK_OFF[0] = false;
			return HEAD_NAMES_OFF[0] + tRecorderColumns[0] + ": " + HEAD_NAMES_OFF[0]
					+ "产品无效（第"+(a+2)+"行）！";
		}
		if(concentricityCodeList.contains(tRecorderColumns[0].trim())){
			COL_CHECK_OFF[0] = false;
			return HEAD_NAMES_OFF[0] + tRecorderColumns[0] + ": " 
					+ "同一次导入"+ HEAD_NAMES_OFF[0]+"不能重复（第"+(a+2)+"行）!";
		}
		
/*
		manuview.setGs_id(tRecorderColumns[0].trim());
		manuview.setGs_concentricity_code(tRecorderColumns[1].trim());
		manuview.setGs_enabled_time(tRecorderColumns[2].trim());
		manuview.setGs_recorder_id(String.valueOf(a));//对象编号
		manuview.setGs_product_name(mbean.getGs_manufacture_name());
		manuview.setGs_spec(mbean.getGs_manufacture_spec());
		manuview.setGs_model(mbean.getGs_manufacture_type());
		manuview.setGs_drawing_piece_code(mbean.getGs_drawing_peice_code());
		manuview.setGs_provider_name(pbean.getGs_provider_shortname());
		manuview.setGs_hour(tRecorderColumns[3].trim().length()==1?"0"+tRecorderColumns[3].trim():tRecorderColumns[3].trim());
		manuview.setGs_minute(tRecorderColumns[4].trim().length()==1?"0"+tRecorderColumns[4].trim():tRecorderColumns[4].trim());
		*/
		manuview2 = new ProductTaxData();
		manuview2.setProductCode(tRecorderColumns[0].trim());
		manuview2.setCodeEdition(tRecorderColumns[1].trim());
		manuview2.setTaxType(tRecorderColumns[2].trim());
		concentricityCodeList.add(tRecorderColumns[0].trim());
		
		return aRowText + "匹配成功！";
	}
}
